package xuegao.study.mall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import xuegao.study.mall.common.api.CommonResult;
import xuegao.study.mall.common.api.ResultCode;

import javax.annotation.PostConstruct;

/**
 * sentinel配置限流后的异常
 */
@Configuration
public class SentinelConfiguration {

    /**
     * 作用是重新定义限流之后的异常改为中文(使用该实例之前,相关的初始化工作已经完成)
     */
    @PostConstruct
    private void initBlockHandler() {
        CommonResult<Object> failed = CommonResult.failed(ResultCode.SYSTEM_FLOW_LIMIT);
        BlockRequestHandler blockRequestHandler = (exchange, t) ->
                ServerResponse
                        .status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(failed));
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}
